package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

/**
 * 同步档位系统部门架构至工单系统
 */
class autoGetDepartment implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoGetDepartment.class);

	public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        def httpURL = KHDBConfig.getAPIURL(eliteBean,"getOfficeByMarketId");

        def result = Util.doHttpPost(httpURL, "", "UTF-8", 5000, 0);
        JSONObject JsonDepartment = new JSONObject(result);
        log.info("[获取部门接口调用结果]:" + JsonDepartment);

        int re_status = JsonDepartment.getInt("status")
        if (re_status == 200) {
            JSONArray jsonArray = JsonDepartment.getJSONArray("data");
            int dataArrayLen = jsonArray.length();
            JSONObject dataObject = null;
            for (int i = 0; i < dataArrayLen; i++) {
                dataObject = jsonArray.getJSONObject(i);
                def id = KHUtil.GetJV(dataObject, "id");//部门编号
                def officeName = KHUtil.GetJV(dataObject, "officeName");//部门名称
                def parentCodes = KHUtil.GetJV(dataObject, "parentCode");//上级部门编号
                def status = KHUtil.GetJV(dataObject, "status");//使用状态
                //def createDate = KHUtil.GetJV(dataObject, "createDate");//创建时间
                //def updateDate = KHUtil.GetJV(dataObject, "updateDate");//修改时间
                if(status=='0'){
                    status='1';
                }else if(status=='1'){
                    status='0';
                }

                def dw_rolegroup_id="";
                def rolegroup_id="";
                def re_parentCodes="";
                def parent_rolegroup_id="";

                //查询当前取到的组是否在工单系统存在（组id）
                def selectSql1 = "select DW_ROLEGROUP_ID,ROLEGROUP_ID from ROLEGROUP where DW_ROLEGROUP_ID='" + id + "'";
                List sqlResult = eliteBean.chaxun_sql(selectSql1, 'dataSource');
                log.debug(sqlResult.toString());
                if (sqlResult.size() > 0) {
                    dw_rolegroup_id = sqlResult.get(0).get("DW_ROLEGROUP_ID");
                    rolegroup_id = sqlResult.get(0).get("ROLEGROUP_ID");
                }

                //查询当前取到的父级组是否在工单系统中存在,不存在则新建一个(父级id)
                if (!KHUtil.isNull(parentCodes)) {
                    def selectSql2 = "select ROLEGROUP_ID from ROLEGROUP where DW_ROLEGROUP_ID='" + parentCodes + "'";
                    List sqlResult2 = eliteBean.chaxun_sql(selectSql2, 'dataSource');
                    if (sqlResult2.size() > 0) {
                        parent_rolegroup_id = sqlResult2.get(0).get("ROLEGROUP_ID");
                    }

                    if (parent_rolegroup_id != null) {
                        re_parentCodes = parent_rolegroup_id;
                    } else {
                        if (parentCodes != "0") {
                            //生成六位随机id
                            re_parentCodes = KHUtil.getRandomString(6);
                            def insertSql5 = "INSERT INTO ROLEGROUP (ROLEGROUP_ID,DW_ROLEGROUP_ID,STATUS,CREATEDDATE) VALUES('" + re_parentCodes + "','" + parentCodes + "','" + 0 + "',now())";
                            eliteBean.update(insertSql5, 'dataSource');
                        }
                    }
                }

                if (KHUtil.isNull(dw_rolegroup_id) && KHUtil.isNull(rolegroup_id)) {

                    def ram_id = KHUtil.getRandomString(6).toUpperCase();//随机id
                    def insertSql1 = "INSERT INTO ROLEGROUP (ROLEGROUP_ID,DW_ROLEGROUP_ID,ROLEGROUPDESCRIPTION,STATUS,PARENT_ROLEGROUPID,CREATEDDATE) VALUES('" + ram_id + "','" + id + "','" + officeName + "','" + status + "','" + re_parentCodes + "',now())";
                    def dataresult = eliteBean.update(insertSql1, 'dataSource');
                    log.debug("执行ROLEGROUP数据新增SQL结果:" + dataresult.toString());

                    def insertsql3="INSERT INTO mprojectrolegroup(ROLEGROUP_ID, MPROJECT_ID, MPROJECTROLEGROUP_ID) VALUES ('" + ram_id + "', 'MMYSQL', uuid())";
                    def dataresult3 = eliteBean.update(insertsql3, 'dataSource');
                    log.debug("执行mprojectrolegroup数据新增SQL结果:" + dataresult3.toString());

                    if (!KHUtil.isNull(parentCodes) && parentCodes != "0") {
                        def insertSql2 = "INSERT INTO authority_relationship ( AUTHORITY_ID, HIGHER, HIGHERFLAG, LOWER, LOWERFLAG ) VALUES( uuid(), '" + re_parentCodes + "', 0, '" + ram_id + "', 0 )";
                        def dataresult2 = eliteBean.update(insertSql2, 'dataSource');
                        log.debug("执行authority_relationship数据新增SQL结果:" + dataresult2.toString());
                    }

                } else {
                    def updateSql1 = "UPDATE ROLEGROUP SET ROLEGROUPDESCRIPTION='" + officeName + "', STATUS='" + status + "', PARENT_ROLEGROUPID='" + re_parentCodes + "' , MODIFIEDDATE=now() WHERE ROLEGROUP_ID='" + rolegroup_id + "' ";
                    def dataresult3 = eliteBean.update(updateSql1, 'dataSource');
                    log.debug("执行ROLEGROUP数据更新SQL结果:" + dataresult3.toString());

                    def updateSql3 = "delete from authority_relationship where lower='" + rolegroup_id + "' and HIGHERFLAG='0' and LOWERFLAG='0'";
                    def row = eliteBean.update(updateSql3, 'dataSource');
                    log.debug("删除authority_relationship层级:" + rolegroup_id + "|" + row);

                    if (!KHUtil.isNull(parentCodes)) {
                        def insertSql4 = "INSERT INTO authority_relationship ( AUTHORITY_ID, HIGHER, HIGHERFLAG, LOWER, LOWERFLAG ) VALUES( uuid(), '" + re_parentCodes + "', 0, '" + rolegroup_id + "', 0 )";
                        def dataresult4 = eliteBean.update(insertSql4, 'dataSource');
                        log.debug("执行authority_relationship数据新增SQL结果:" + dataresult4.toString());
                    }
                }
            }
        }
    }

}
